package org.xbzheng.restful_study.dao;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;
import org.xbzheng.restful_study.model.User;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.xbzheng.restful_study.model.User;

import java.util.List;

/**
 * @Created by xiaobing.zheng on 2016/10/28.
 */
@Repository
public class UserDao {

    @PersistenceContext
    private EntityManager entityManager;

    public User findUserByName(final String userName) {
        final Query query = entityManager.createQuery("select u from User u where u.username=?1");
        query.setParameter(1, userName);
        final List<User> results = query.getResultList();
        return results.isEmpty() ? null : results.get(0);
    }

    public List<User> findAllUser() {
        final Query query = entityManager.createQuery("select u from User u");
        return query.getResultList();
    }

    public User save(final User user) {
        return entityManager.merge(user);
    }

    public void remove(final List<Integer> ids) {
        final Query query = entityManager.createNativeQuery("delete from t_user where id in (?1)");
        query.setParameter(1, ids);

        query.executeUpdate();
    }
}
